package com.sangjie.souyidai.https;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.ByteArrayBuffer;

public class XiangShang implements IXiangShang{
	
	private static String USER_NAME = "13810114052";
	private static String PASS_WORD = "123qweASD";
	
	private CloseableHttpClient httpclient;

	public static void main(String[] args) throws Exception {
		
		signIn();
		
//        XiangShang xs = new XiangShang();
//		xs.login(httpclient);
//		xs.sign(httpclient);
        
        
//        String param1 = "event=eJytUl1PE0EU%2FS%2F7LJudnd3Z2b6hYOKbT74YH%2FarsSEhSBcSbUgqmH6R2q3JkhJAS4VWorY80AgL%2BGs6s7v%2FwjvdRgOJUaL7MnPPnHPPuTtTkqwlKSdZhmUQByPTsTzN8xTLpo6tYBcRhxCq2dI9qegurQNzXZWxjLJaCJdd2LsFF%2FY2Ney8h0BJCHbyxNI819RdlLcVWyUGAaKzDDyhdtamEnUeaaZu6LpiPkRogeB5g2jk%2FuIi1heMB4oKTL8oJBpVsUFMRGVsCvDligdw0bf8QlEEsHxLyj0tSZ4PsLMmMP%2BVMKBUEd%2FtRooiq6ro5E1zsChMtz4lrX3WDHm3xWpV3uzB6cqqlCtJgMR7Q6Cl%2FZ30cCxtwPRTWdZNU3VTpgoB%2FE4BMNZ%2BBoh3L9Pdyly2gEd6IOz%2F2QUZMtLRbZe0XOfbJ1nBdy7YVevXqAfHPAoEde%2BMvz2ONy9Y9TJj%2FpexxQWqNwKx63AuW3gtYI0Pfxy74Ob%2FxgXf6ZXNpu%2BM48EpKJ6vui8oKKhJRdj4az2OBoA%2FefRY9I0HI1arQA37pPc53SzHQSU5602iiIenGc47Ixb02fA9C5rJ8CgZvQYcQDhiQXty3kiGh6z27gY5aLOjweR7V7zIoC%2BY5YjVzpPrL8nwJGNmRmm1PROGH3m3yhthMn4zQ%2BrbfD9irW%2Fif2CKFIQ0RRczTq46fKsL%2FQTxt5f5bOMHQ01vSg%3D%3D&compress=1&method=event_statis_srv.upload";
//        String param2 = "event=eJyVkctKAzEUht8laynJJJNJuvMK7ly5EReZyRRLQdSOgpaCN7Qq4lQodCFSL1hEbV0oyqA%2BTTMd38ITx43gxlmd8%2BX7czlTQ6qCikh5yuMBJTJQIQtDrHwR%2BJhqwgPOBfPRCKrqyhqYa06BFkje2%2BCihlqXNdS%2B8PxSSCDJOQ1KXLFQS1eTko99h3scxGARPJsOVr8jzihh0vVcF8spQiY4HfU442OTk9Sd8MaxA2ZUtREmHOpxSWSBSGbp%2BlIIvBqpqFy1N1CRQsW5GgojwGVdss6GPUEIbL%2B%2FduLuv26ytIKKNZS2n4fdR0gsrOhlAQkhhX3R8OFgmHSBz07PUNt3%2B6axBz3U2eXd5%2FbmMN7Lni4HSZK2HnOetvsmvjG9cxMfZ73rrL8FHCAsmbg5eD3MehemcfpLjpvmujv46ACE1pqbiWm8Zu%2F3We82N%2FODPvebP8HWVdrZTw9b2fPuDzk4Ss8Sc%2FJiB0IFwYQw7No3Dt7a6U4H9rNiHf7y93DyoTHHlQWBOarP178AFFvIRQ%3D%3D&compress=1&method=event_statis_srv.upload";
        
//        xs.mobileLogin(httpclient, param1);
//        xs.mobileLogin(httpclient, param2);
//        xs.token(httpclient);
//		xs.doPuzzle(xs.httpclient, 11);
	}
	
	public XiangShang() {
		try {
			SSLContextBuilder builder = new SSLContextBuilder();
		    builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
		    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
		    ConnectionConfig connectionConfig = ConnectionConfig.custom().setBufferSize(4128).build();
		    httpclient = HttpClients.custom()
		            .setDefaultConnectionConfig(connectionConfig).setSSLSocketFactory(sslsf).build();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void signIn() {
		XiangShang xs = new XiangShang();
		xs.login();
		xs.sign();
	}
	
	public void login() {
		try {
			login(httpclient);
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	public void sign() {
		try {
			sign(httpclient);
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	private CloseableHttpResponse login(CloseableHttpClient httpclient) throws Exception {
		HttpPost httpPost = new HttpPost("https://www.xiangshang360.com/xweb/login/check");
        List<NameValuePair> logingFormparams = new ArrayList<NameValuePair>();
        logingFormparams.add(new BasicNameValuePair("username", USER_NAME));
        logingFormparams.add(new BasicNameValuePair("password", PASS_WORD));
        logingFormparams.add(new BasicNameValuePair("validateCode", ""));

        httpPost.setHeader("Connection", "keep-alive");
        httpPost.setHeader("Accept", "application/json, text/javascript, */*; q=0.01");
        httpPost.setHeader("Origin", "https://www.xiangshang360.com");
        httpPost.setHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36");
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        httpPost.setHeader("Referer",
                "https://www.xiangshang360.com/xweb/logout");
        httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
        httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
        httpPost.setHeader("Cache-Control", "no-cache");
        httpPost.setHeader("X-Requested-With", "XMLHttpRequest");
        httpPost.setHeader("Host", "www.xiangshang360.com");
        
        UrlEncodedFormEntity requestLoginEntity = new UrlEncodedFormEntity(logingFormparams, Consts.UTF_8);
        httpPost.setEntity(requestLoginEntity);
        CloseableHttpResponse response = httpclient.execute(httpPost);
        try {
            HttpEntity entity = response.getEntity();
            InputStream inputStream = entity.getContent();
            ByteArrayBuffer bab = new ByteArrayBuffer(1024);
            int b;
            while ((b = inputStream.read()) != -1) {
                bab.append(b);
            }

            String str = new String(bab.toByteArray(), "utf-8");
            System.out.println(str);
            System.out.println("LOGIN SUCCESS !");
        } finally {
            response.close();
        }
        return response;
	}
	
	// 签到
    private CloseableHttpResponse sign(CloseableHttpClient httpclient) throws Exception {
    	HttpGet httpGet = new HttpGet("https://www.xiangshang360.com/xweb/daily/signin?_=" + System.currentTimeMillis());

    	httpGet.setHeader("Connection", "keep-alive");
    	httpGet.setHeader("Accept", "application/json, text/javascript, */*; q=0.01");
    	httpGet.setHeader("X-Requested-With", "XMLHttpRequest");
    	httpGet.setHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36");
    	httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    	httpGet.setHeader("Referer",
                "https://www.xiangshang360.com/xweb/my/account");
    	httpGet.setHeader("Accept-Encoding", "gzip, deflate");
    	httpGet.setHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
    	httpGet.setHeader("cache-control", "no-cache");
    	httpGet.setHeader("pragma", "no-cache");
    	httpGet.setHeader("Host", "www.xiangshang360.com");
        
        CloseableHttpResponse response = httpclient.execute(httpGet);
        try {
            HttpEntity entity = response.getEntity();
            InputStream inputStream = entity.getContent();
            ByteArrayBuffer bab = new ByteArrayBuffer(1024);
            int b;
            while ((b = inputStream.read()) != -1) {
                bab.append(b);
            }

            String str = new String(bab.toByteArray(), "utf-8");
            System.out.println(str);
            System.out.println("SIGN SUCCESS !");
        } finally {
            response.close();
        }
        return response;
    }
    
    
    private CloseableHttpResponse mobileLogin(CloseableHttpClient httpclient, String params) throws Exception {
    	HttpGet httpGet = new HttpGet("http://zhugeio.xiangshang360.com/apipool?" + params);
    	CloseableHttpResponse response = httpclient.execute(httpGet);
        try {
            HttpEntity entity = response.getEntity();
            InputStream inputStream = entity.getContent();
            ByteArrayBuffer bab = new ByteArrayBuffer(1024);
            int b;
            while ((b = inputStream.read()) != -1) {
                bab.append(b);
            }

            String str = new String(bab.toByteArray(), "utf-8");
            System.out.println(str);
            System.out.println("SIGN SUCCESS !");
        } finally {
            response.close();
        }
        return response;
    }
    
    private CloseableHttpResponse token(CloseableHttpClient httpclient) throws Exception {
    	HttpPost httpPost = new HttpPost("http://182.92.228.160:80/xiangshang360/xiangshang/token");
    	
    	httpPost.setEntity(new StringEntity("{\"grant_type\":\"password\",\"username\":\"xstxnxxqnwa\",\"password\":\"111111\"}"));
    	
    	CloseableHttpResponse response = httpclient.execute(httpPost);
        try {
            HttpEntity entity = response.getEntity();
            InputStream inputStream = entity.getContent();
            ByteArrayBuffer bab = new ByteArrayBuffer(1024);
            int b;
            while ((b = inputStream.read()) != -1) {
                bab.append(b);
            }

            String str = new String(bab.toByteArray(), "utf-8");
            System.out.println(str);
            System.out.println("SIGN SUCCESS !");
        } finally {
            response.close();
        }
        return response;
    }
    
    private CloseableHttpResponse doPuzzle(CloseableHttpClient httpclient, int step) throws Exception {
    	HttpGet httpGet = new HttpGet("http://m.xiangshang360.com/wap/puzzle/doPuzzle?step=" + step + "&_=" + System.currentTimeMillis());

    	httpGet.setHeader("Accept", "application/json, text/javascript, */*; q=0.01");
    	httpGet.setHeader("X-Requested-With", "XMLHttpRequest");
    	httpGet.setHeader("User-Agent",
                "Mozilla/5.0 (Linux; Android 5.1.1; OPPO R9 Plustm A Build/LMY47V; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/43.0.2357.121 Mobile Safari/537.36");
    	httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    	httpGet.setHeader("Referer",
                "http://m.xiangshang360.com/html/newwap/find/find.html");
    	httpGet.setHeader("Accept-Encoding", "gzip, deflate");
    	httpGet.setHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
    	httpGet.setHeader("Host", "m.xiangshang360.com");
    	httpGet.setHeader("Cookie", "_zg={\"uuid\": \"1591fb72e16291-0494fa84d-3045572b-38400-1591fb72e183cd\",\"sid\": 1482295815.708,\"updated\": 1482295815.708,\"info\": 1482295815733}; responseTimeline=286; JSESSIONID=AB731087A3E56F6553160A935B945173; Hm_lvt_b9ca1fb98a8894d96844f49ab755e654=1482295731; Hm_lpvt_b9ca1fb98a8894d96844f49ab755e654=1482307832; token=lSql91lNLHYEeQ4MEd820zCWVZc6Dxncu2m79cWbJpkmvRzMRvbwrgMAnKQ4DR7rCVM9wc6mLOAc/DQzn5IgcX1gHHWZA2jfF3W5k7gPeXvmeoMOZ7TMjZ7N2hoQ8c4H; __ads_session=kC84iOzy1QieQLkL7wA=");
        
        CloseableHttpResponse response = httpclient.execute(httpGet);
        try {
            HttpEntity entity = response.getEntity();
            InputStream inputStream = entity.getContent();
            ByteArrayBuffer bab = new ByteArrayBuffer(1024);
            int b;
            while ((b = inputStream.read()) != -1) {
                bab.append(b);
            }

            String str = new String(bab.toByteArray(), "utf-8");
            System.out.println(str);
            System.out.println("SIGN SUCCESS !");
        } finally {
            response.close();
        }
        return response;
    }
	
}
